package com.tepth.busfix.download;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.widget.Toast;

import com.tepth.busfix.bean.reponse.Version;
import com.tepth.busfix.network.ApiModel;
import com.tepth.busfix.network.Network;
import com.tepth.busfix.tools.AppUtils;
import com.tepth.busfix.tools.SDCardUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

/**
 * Created by zhangyu on 2017/3/29.
 */

public class AppUpdateManager {
    private Context context;

    public AppUpdateManager(Context context) {
        this.context = context;
    }

    private SweetAlertDialog pDialog;

    public void checkVersion(final OnVersionCheckListener listener) {
        pDialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText("正在检测版本信息...");
        pDialog.setCancelable(false);
        pDialog.show();
        Network.getApiService().getVersion("busvm_repair_apk")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<ApiModel<Version>>() {
                    @Override
                    public void onNext(ApiModel<Version> value) {
                        Version version = value.getResult();
                        String code = version.getV3();
                        final String url = version.getV2();
                        pDialog.changeAlertType(SweetAlertDialog.WARNING_TYPE);
                        if (Float.parseFloat(code) > AppUtils.getVersion(context)
                                && url != null && !url.isEmpty()) {
                            pDialog.showCancelButton(true);
                            pDialog.setTitleText("检测到新版本");
                            pDialog.setContentText("版本信息:" + code);
                            pDialog.setConfirmText("更新");
                            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    download(url, context);
                                }
                            });
                            pDialog.setCancelText("取消");
                        } else {
                            pDialog.dismiss();
                            //  Toast.makeText(context, "已是最新版本!", Toast.LENGTH_SHORT).show();
                            if (listener != null) {
                                listener.onSucceed("已是最新版本!");
                            }
                        }
                    }


                    @Override
                    public void onError(Throwable e) {
                        pDialog.dismiss();
                        Toast.makeText(context, "版本信息获取失败", Toast.LENGTH_SHORT).show();
                        if (listener != null) {
                            listener.onFailed("版本信息获取失败");
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void download(String url, Context context) {
        if (SDCardUtils.isSDCardEnable()) {
            downloadFile(url, context);
        } else {
            pDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
            pDialog.showCancelButton(false);
            pDialog.setConfirmText("确定");
            pDialog.setTitleText("下载失败");
            pDialog.setContentText("请插入sd卡!");
            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    pDialog.dismiss();
                }
            });
        }
    }

    private static final String apkName = "/busfix.apk";

    /**
     * 下载apk文件
     *
     * @param url
     */
    private void downloadFile(String url, final Context context) {
        pDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
        pDialog.showCancelButton(false);
        pDialog.showContentText(false);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.getProgressHelper().stopSpinning();
        OkHttpUtils.get().url(url).build().execute(new FileCallBack(SDCardUtils.getPublicDirectory(), apkName) {
            @Override
            public void onError(Call call, Exception e, int id) {
                pDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
                pDialog.setTitleText("下载失败");
                pDialog.showCancelButton(false);
                pDialog.setConfirmText("确定");
                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        pDialog.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(File response, int id) {
                File file = new File(SDCardUtils.getPublicDirectory() + apkName);
                final Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
                pDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                pDialog.setTitleText("下载完成!");
                pDialog.setConfirmText("安装");
                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        context.startActivity(intent);
                    }
                });
            }

            @Override
            public void inProgress(float progress, long total, int id) {
                pDialog.setTitleText("已下载" + (int) (progress * 100) + "%");
                pDialog.getProgressHelper().setProgress(progress);
            }
        });

    }

    public interface OnVersionCheckListener {
        void onSucceed(String msg);

        void onFailed(String msg);
    }
}
